package com.cuit.mimall.controller.backend;

import com.cuit.mimall.common.R;
import com.cuit.mimall.entity.Category;
import com.cuit.mimall.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @author TeaWu
 * @folder 后台/商品分类
 */
@RestController("backendCategoryController")
@RequestMapping("/api/v1/backend/category")
public class CategoryController {
    private final ICategoryService categoryService;

    @Autowired
    public CategoryController(ICategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 添加商品分类
     *
     * @param category 分类信息
     */
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> add(@RequestBody Category category) {
        return categoryService.add(category);
    }

    /**
     * 修改商品分类
     *
     * @param category 分类信息
     * @return R<?> 修改结果
     */
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> update(@RequestBody Category category) {
        return categoryService.update(category);
    }

    /**
     * 删除分类
     *
     * @param ids 分类id
     * @return R<?> 删除结果
     */
    @DeleteMapping("/delete")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> delete(@RequestBody Integer[] ids) {
        if (ids.length == 0) {
            return R.error("请选择要删除的分类");
        }
        return categoryService.delete(ids);
    }

    /**
     * 分页获取所有分类
     *
     * @param pageNumber 页码
     * @param pageSize   每页数量
     * @return R<?> 分类列表
     */
    @RequestMapping("/getAll")
    public R<?> getAll(@RequestParam(defaultValue = "1") Integer pageNumber,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        return categoryService.getAll(pageNumber, pageSize);
    }

    /**
     * 根据id获取分类
     *
     * @param id 分类id
     * @return R<?> 分类信息
     */
    @GetMapping("/getById")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> getById(@RequestParam Integer id) {
        Category category = categoryService.getById(id);
        return R.ok(category);
    }

    /**
     * 获取所有分类
     *
     * @return R<?> 分类列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
    public R<?> list() {
        return R.ok(categoryService.list());
    }
}
